package com.wzs.rpc.registry;

import com.wzs.rpc.serializer.JDKSerializer;
import com.wzs.rpc.serializer.Serializer;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.ServiceLoader;

@Slf4j
public class RegistryFactory {
    private static final Map<String, Object> instanceCache = new HashMap<>();
    private static final Registry DEFAULT_SERIALIZER = new EtcdRegistry();

    //饿汉，加载时便初始化，避免多线程下的安全问题
    static {
        ServiceLoader<Registry> registrys = ServiceLoader.load(Registry.class);
        for (Registry registry : registrys) {
            instanceCache.put(registry.getClass().getName(), registry);
        }
        log.debug("SPI加载Registry, 实例个数为 {}", instanceCache.size());
    }

    public static Registry getInstance(String registry) {
        return (Registry) instanceCache.getOrDefault(registry, DEFAULT_SERIALIZER);
    }
}
